package com.fzhucc.modules.sendDataToQz.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class RequestUtil {

    /**
     * 签名
     */
    public static String sign = "";
    /**
     * 对接系统ID
     */
    public static String sysid = "";
    /**
     * 请求随机数
     */
    public static String reqid = "";
    /**
     * 请求时间
     */
    public static String reqtime = "";

    /**
     * 请求方公钥
     */
    public static String PUB_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxwIIJ5ZF7/6uYIvoOhNnUXmZFZr79Ub1rBWuLE0yRcB9veGEhqPRtE1Z12ghicWXwzr/Fd8slHr/FvPD95pjMZtjn9JPhMmSScepwpEMo4KkH3dmHqPQPF8gLzZ2ee/263pspGtYraSYWXUsz0ZhTdHC/65C+uut2Y6lozE+IyBhmt1DUe/ePw1yL2sPFl1SnYhrsmLlT2fEsM8MsmI9VvheTDlR1pC/alnBlnHYsCjLhO1K2u6pYN2o9bROvBTyuza1jmSMNCKk+NK5KaWZLjW/JdjKapMZ0J9pu+7tvSn4h29eHpBtRzNjDgU31By9MLQjkPxYFVu2v3r3ZOyHaQIDAQAB";
    /**
     * 请求方私钥
     */
    public static String PRI_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDHAggnlkXv/q5gi+g6E2dReZkVmvv1RvWsFa4sTTJFwH294YSGo9G0TVnXaCGJxZfDOv8V3yyUev8W88P3mmMxm2Of0k+EyZJJx6nCkQyjgqQfd2Yeo9A8XyAv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jkT+iLyxh+vbhwKBgH+7/a4aKGbMFwgIK1eTuRdZAUqhojKGDUfN1FbqLOHqLTaKXtywRXuZdwnfLHRJBIV8xJxAO839cqEUrS4NscTpwyQWPEM7VPANRrP5MfWpQS1x/vo3W0rpD6U2dEmH1Yk2SmejlAhuFm5Te3BR3CjbRUWDTanlk7GtlroNIaedAoGBAN2/6JkO4+TFaL/26fzV7m4rBTp10B8FHwbJOSj7h2uHK0rjxIkdv7/6cTpcZtDhsvYWQLai68Nwnc7Y+nP64zBfBE6wO9qzyUZW0XtDMhpj0xy0MlFohdr+YnMfOHkQeZ+uQBefOpz8D0Kq9KrNh8tVhrJPpyZqABZnoMdFsvnU";
    /**
     * 被请求方公钥
     */
    public static final String pub_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo3SFd8cJEHpW4eDqqazOSVWkJGd8cedpBP3iLfiTbMep91V0gEBKbJZm25UoWzLmXbK6/+8rO5w6RogjS7kL8t4FlwBZBhujO8HTokVgJRFhuDclcnnwtbb8E6mMsnhwIlonOrl55DKxddYr0PMt3Xbd42fJLFmn8pCoFCkPd8hKZIfkCmMWkFiV0dzFw6sD6HoP6GS7bk8b+35p+eSHNEPoQ+YziGBoISHuR0AbgGfFuUCoyfOQYrhHhBZ6QQ29DTGrvidEsw4I6QVUOkRRs58ma8IRD+9XI9YmNVMNGA3pxkDLpMDnI4wcq8bpeid+d8d+ASiw4ii7G1biDEwoIQIDAQAB";
    /**
     * 被请求方私钥
     */
    public static final String pri_key = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCjdIV3xwkQelbh4OqprM5JVaQkZ3xx52kE/eIt+JNsx6n3VXSAQEpslmbblShbMuZdsrr/7ys7nDpGiCNLuQvy3gWXAFkGG6M7wdOiRWAlEWG4NyVyefC1tvwTqYyyeHAiWic6uXnkMrF11ivQ8y3ddt3jZ8ksWafykKgUKQ93yEpkh+QKYxaQWJXR3MXDqwPoeg/o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kGcfXWVozhM1hJvdcpK3M0ZBI2McvvDsLflW++qNIPIx/n2u0/SH/kyfy3tuG7OxjrHXTbD5fBm2p6klH49QBxmxl+Jey0RwYQJ/uykeLTSgyAqKGNxYvaRKVCQKBgQDRBcMXw0RuNN26KJMWiwZ6mPbqbmBnWb4RtB/SHLY+vLKzVxcYAmN+d8BIA+rEAEk62iIF5lqTz/XswB4AmmXLEBd7I7wwwbCiZTApIV1aSXujvQ4szv9dAK26Em3/1QVZos4Uxfv+6YR/o5Ipu3vPygeDSRoedQZOxc3ZJ0aqNw==";


    /**
     * 验证必要参数
     *
     * @throws Exception 验证异常
     */
    public static void check() throws Exception {
        reqid = UUID.randomUUID().toString();
        reqtime = DateUtils.dateTimeNow();

        if (StringUtils.isEmpty(sysid)) {
            throw new Exception("sysid不能为空");
        }
    }


    /**
     * 设置相关请求头参数
     *
     * @param headerMap 请求头map
     * @param json      请求参数
     */
    public static void setHeaders(Map<String, String> headerMap, String json) {

        String signLine = json + "|" + sysid + "|" + reqid + "|" + reqtime;
        System.out.println("signLine=" + signLine);
        sign = SHA256withRSAUtil.sign2Base64(PRI_KEY, signLine);
        System.out.println("签名" + sign);

        headerMap.put("zqxsign", sign);
        headerMap.put("zqxsysid", sysid);//appid
        headerMap.put("zqxreqid", reqid);
        headerMap.put("zqxreqtime", reqtime);
    }


    /**
     * 以post方式调用第三方接口
     *
     * @param url     请求地址
     * @param headers 请求头
     * @param json    请求体
     * @return 请求结果
     */
    public static String doPost(String url, Map<String, String> headers, String json) throws Exception {
        check();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        try {
            //1.创建httpClient对象
            httpClient = HttpClients.createDefault();
            //2.创建httpPost对象
            HttpPost httpPost = new HttpPost(url);
            //2.1对象设置请求头
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

            setHeaders(headers, json);

            //设置自定义请求头
            if (!headers.isEmpty()) {
                headers.forEach(httpPost::setHeader);
            }
            //2.2对象设置请求和传输超时时间
            RequestConfig.Builder custom = RequestConfig.custom();
            //超时时间10秒
            custom.setSocketTimeout(10000);
            custom.setConnectTimeout(10000);
            custom.setConnectionRequestTimeout(10000);
            httpPost.setConfig(custom.build());
            //2.3对象设置请求参数
            httpPost.setEntity(new StringEntity(json, StandardCharsets.UTF_8));
            //3.使用httpClient发起请求并响应获取repsonse
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            //4.解析响应，获取数据
            //判断状态码是否是200
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == statusCode || HttpStatus.SC_BAD_REQUEST == statusCode) {
                result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(result);
            }
            System.out.println(httpResponse.getStatusLine());
            System.out.println(httpResponse.getProtocolVersion());
            System.out.println(Arrays.toString(httpResponse.getAllHeaders()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}
